package com.sjs.flow.controller;

import com.sjs.flow.service.ImageService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

/**
 * @author uto_dev_008
 * @desc
 * @since 2022/7/26 17:15
 * Copyright (c) 2021 南京友拓信息技术有限公司 All rights reserved
 */

@Api(tags = "流程图")
@RestController
@RequestMapping("/flow/diagram")
public class DiagramController {
    protected static Logger LOG = LoggerFactory.getLogger(DiagramController.class);

    @Autowired
    ImageService imageService;

    /**
     * 绘制流程图
     *
     * @param response
     * @param processId
     * @throws Exception
     */
    @RequestMapping(value = "historyDiagram", method = RequestMethod.GET)
    public void genHistoryDiagram(HttpServletResponse response, String processId) throws Exception {
        OutputStream responseStream = null;
        try {
            BufferedImage bufferedImage = imageService.generateImageByProcInstId(processId);
            response.setContentType("image/png");

            responseStream = response.getOutputStream();
            ImageIO.write(bufferedImage, "png", responseStream);
            responseStream.flush();
            response.flushBuffer();
        } catch (Exception e) {
            LOG.error("流程跟踪图生成失败： {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (responseStream != null) {
                responseStream.close();
            }
        }
    }
}
